package com.tqjc.system.core.socket;

import com.tqjc.system.common.constant.GlobalConstant;
import com.tqjc.system.core.threadpool.ThreadPoolManager;
import com.tqjc.system.core.util.SpringUtils;
import com.tqjc.system.system.service.SysBusinessTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 86195
 * @version 1.0
 * @description MES报文接受处理类
 * @date 2023/10/12 10:37
 */
@Slf4j
public class MESSocketRecvOperator {



    private static ServerSocket serverSocket;

    private static SysBusinessTaskService sysBusinessTaskService;


        public static Lock lock = new ReentrantLock();


    public static void connet() throws IOException {
        log.info("服务端启动监听");
        serverSocket = new ServerSocket(9009);
        sysBusinessTaskService = SpringUtils.getBean("SysBusinessTaskService");
        new Thread(new Runnable() {
            @Override
            public void run() {
                log.info("==============MESSocketRecvOperator 服务端启动监听===============");
                while (true){
                    try {
                        Socket accept = serverSocket.accept();
                        ThreadPoolManager.getInstance().execute(new RecvThread(accept));
                    } catch (Exception e){
                        e.printStackTrace();
                        log.error("监听线程出现异常",e);
                    }

                }
            }
        }).start();
    }

    @Slf4j
    private static class RecvThread implements Runnable {

        private Socket socket;

        public RecvThread(Socket socket) {
            this.socket = socket;
        }

        public RecvThread() {
        }

        @Override
        public void run() {

            log.info("==============MESSocketRecvOperator 开始接收数据===============");
            try(InputStream inputStream = socket.getInputStream()){
                if(inputStream != null){
                    byte[] b = new byte[5000];
                    int len = inputStream.read(b);
                    String content = new String(b, 0, len);
                    log.info("接受内容是:{}",content);
                    String msgNo = content.substring(4, 10);
                    if(GlobalConstant.MSG_NO_HEARTBEAT.equals(msgNo)){
                        log.info("心跳信息过滤");
                        return;
                    }
                    //应答报文
//                    sendMsg(sendResponseMsg(msgNo));
                    sysBusinessTaskService.accept(content);
                }


            } catch (Exception e) {
                log.error("MESSocketRecvOperator接受数据线程出现异常",e);
                e.printStackTrace();
            }

        }
    }


    public static String sendResponseMsg(String msgNo){
        Date date = new Date();
        String dateStr = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
        String spaces = StringUtils.repeat(" ", 80);
        StringBuilder sb = new StringBuilder(msgNo).append(dateStr).append(GlobalConstant.MSG_CAR_CODE).append(GlobalConstant.MSG_MES_CODE)
                .append(GlobalConstant.MSG_TRANSFER_CODE_A).append(spaces).append(GlobalConstant.MSG_END_CODE);
        String s = sb.toString();
        int length = s.length() + 4;
        DecimalFormat df = new DecimalFormat("0000");
        String lengthStr = df.format(length);
        return lengthStr + s;
    }


        // 发送消息
    public static void sendMsg(String msg) throws IOException {
        OutputStream outStream = null;
        try {
            lock.lock();
            Socket accept = serverSocket.accept();
            outStream = accept.getOutputStream();

            byte[] bytes = msg.getBytes("UTF-8");
            outStream.write(bytes);
            outStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            outStream.close();

        }
    }
}
